<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>角色管理 - 人事管理系统</title>
    <!-- 引入Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- 引入Bootstrap图标 -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
    <style>
        .navbar-brand {
            font-weight: bold;
            font-size: 1.5rem;
        }
        .footer {
            margin-top: 50px;
            padding: 20px 0;
            color: #6c757d;
            border-top: 1px solid #dee2e6;
        }
        .table-actions {
            white-space: nowrap;
        }
        .search-bar {
            margin-bottom: 20px;
        }
        .pagination {
            justify-content: center;
            margin-top: 20px;
        }
        .badge-pill {
            margin-right: 5px;
            margin-bottom: 5px;
        }
        .permission-group {
            margin-bottom: 15px;
        }
    </style>
</head>
<body>
    <!-- 导航栏 -->
    <div th:replace="~{layout/header :: navbar(active='role')}"></div>

    <!-- 主要内容 -->
    <div class="container mt-4">
        <div class="row">
            <div class="col-md-12">
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <h2>角色管理</h2>
                    <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addRoleModal">
                        <i class="bi bi-plus-circle me-1"></i>新增角色
                    </button>
                </div>
                
                <!-- 搜索栏 -->
                <div class="card search-bar">
                    <div class="card-body">
                        <form id="searchForm" class="row g-3">
                            <div class="col-md-4">
                                <label for="roleName" class="form-label">角色名称</label>
                                <input type="text" class="form-control" id="roleName" name="name" placeholder="请输入角色名称">
                            </div>
                            <div class="col-md-4 d-flex align-items-end">
                                <button type="submit" class="btn btn-primary me-2">
                                    <i class="bi bi-search me-1"></i>搜索
                                </button>
                                <button type="button" class="btn btn-secondary" id="resetBtn">
                                    <i class="bi bi-arrow-counterclockwise me-1"></i>重置
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
                
                <!-- 角色列表 -->
                <div class="card">
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-striped table-hover">
                                <thead>
                                    <tr>
                                        <th>ID</th>
                                        <th>角色名称</th>
                                        <th>权限</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody id="roleTableBody">
                                    <!-- 角色数据将通过JavaScript动态加载 -->
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 新增角色模态框 -->
    <div class="modal fade" id="addRoleModal" tabindex="-1" aria-labelledby="addRoleModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="addRoleModalLabel">新增角色</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="addRoleForm">
                        <div class="mb-3">
                            <label for="addRoleName" class="form-label">角色名称</label>
                            <input type="text" class="form-control" id="addRoleName" name="name" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">权限选择</label>
                            <div id="addPermissionContainer" class="border p-3 rounded">
                                <!-- 权限选择框将通过JavaScript动态生成 -->
                                <div class="text-center">
                                    <div class="spinner-border text-primary" role="status">
                                        <span class="visually-hidden">Loading...</span>
                                    </div>
                                    <p>加载权限列表中...</p>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="saveRoleBtn">保存</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 编辑角色模态框 -->
    <div class="modal fade" id="editRoleModal" tabindex="-1" aria-labelledby="editRoleModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="editRoleModalLabel">编辑角色</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="editRoleForm">
                        <input type="hidden" id="editRoleId" name="id">
                        <div class="mb-3">
                            <label for="editRoleName" class="form-label">角色名称</label>
                            <input type="text" class="form-control" id="editRoleName" name="name" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">权限选择</label>
                            <div id="editPermissionContainer" class="border p-3 rounded">
                                <!-- 权限选择框将通过JavaScript动态生成 -->
                                <div class="text-center">
                                    <div class="spinner-border text-primary" role="status">
                                        <span class="visually-hidden">Loading...</span>
                                    </div>
                                    <p>加载权限列表中...</p>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="updateRoleBtn">更新</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 确认删除模态框 -->
    <div class="modal fade" id="deleteRoleModal" tabindex="-1" aria-labelledby="deleteRoleModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="deleteRoleModalLabel">确认删除</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <p>您确定要删除这个角色吗？此操作不可逆。</p>
                    <input type="hidden" id="deleteRoleId">
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-danger" id="confirmDeleteBtn">删除</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 页脚 -->
    <div th:replace="~{layout/footer :: footer}"></div>
    
    <!-- 通用脚本 -->
    <div th:replace="~{layout/footer :: scripts}"></div>
    
    <!-- 角色管理脚本 -->
    <script>
        $(document).ready(function() {
            // 加载角色列表
            function loadRoles() {
                // 发送AJAX请求获取角色列表
                $.ajax({
                    url: '/roles/list',
                    type: 'GET',
                    success: function(response) {
                        if (response.code === 1) {
                            const roles = response.data;
                            
                            // 清空表格
                            $('#roleTableBody').empty();
                            
                            // 遍历角色数据，构建表格行
                            if (roles && roles.length > 0) {
                                roles.forEach(function(role) {
                                    // 构建权限标签
                                    let permissionLabels = '';
                                    if (role.permissions && role.permissions.length > 0) {
                                        role.permissions.forEach(function(permission) {
                                            permissionLabels += `<span class="badge bg-primary badge-pill">${permission.name}</span>`;
                                        });
                                    } else {
                                        permissionLabels = '<span class="text-muted">无权限</span>';
                                    }
                                    
                                    const row = `
                                        <tr>
                                            <td>${role.id}</td>
                                            <td>${role.name}</td>
                                            <td>${permissionLabels}</td>
                                            <td class="table-actions">
                                                <button class="btn btn-sm btn-primary edit-role" data-id="${role.id}">
                                                    <i class="bi bi-pencil"></i> 编辑
                                                </button>
                                                <button class="btn btn-sm btn-danger delete-role" data-id="${role.id}">
                                                    <i class="bi bi-trash"></i> 删除
                                                </button>
                                            </td>
                                        </tr>
                                    `;
                                    $('#roleTableBody').append(row);
                                });
                            } else {
                                $('#roleTableBody').append('<tr><td colspan="4" class="text-center">暂无数据</td></tr>');
                            }
                        } else {
                            alert('加载角色列表失败：' + response.msg);
                        }
                    },
                    error: function() {
                        alert('加载角色列表失败，请稍后再试');
                    }
                });
            }
            
            // 加载权限列表
            function loadPermissions(containerId, selectedPermissions = []) {
                $.ajax({
                    url: '/permissions/list',
                    type: 'GET',
                    success: function(response) {
                        if (response.code === 1) {
                            const permissions = response.data;
                            const $container = $(`#${containerId}`);
                            $container.empty();
                            
                            if (permissions && permissions.length > 0) {
                                // 构建权限选择框
                                permissions.forEach(function(permission) {
                                    const isChecked = selectedPermissions.some(p => p.id === permission.id);
                                    const permissionItem = `
                                        <div class="form-check mb-2">
                                            <input class="form-check-input permission-checkbox" type="checkbox" 
                                                id="${containerId}-perm-${permission.id}" 
                                                value="${permission.id}" ${isChecked ? 'checked' : ''}>
                                            <label class="form-check-label" for="${containerId}-perm-${permission.id}">
                                                ${permission.name}
                                            </label>
                                        </div>
                                    `;
                                    $container.append(permissionItem);
                                });
                            } else {
                                $container.html('<p class="text-center">暂无权限数据</p>');
                            }
                        } else {
                            alert('加载权限列表失败：' + response.msg);
                        }
                    },
                    error: function() {
                        alert('加载权限列表失败，请稍后再试');
                    }
                });
            }
            
            // 初始加载角色列表
            loadRoles();
            
            // 新增角色模态框显示事件
            $('#addRoleModal').on('show.bs.modal', function() {
                loadPermissions('addPermissionContainer');
            });
            
            // 保存新角色
            $('#saveRoleBtn').click(function() {
                const name = $('#addRoleName').val();
                
                if (!name) {
                    alert('请填写角色名称');
                    return;
                }
                
                // 获取选中的权限
                const permissionSet = [];
                $('#addPermissionContainer .permission-checkbox:checked').each(function() {
                    permissionSet.push({
                        id: parseInt($(this).val())
                    });
                });
                
                const roleData = {
                    name: name,
                    permissionSet: permissionSet
                };
                
                $.ajax({
                    url: '/roles',
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify(roleData),
                    success: function(response) {
                        if (response.code === 1) {
                            // 关闭模态框
                            $('#addRoleModal').modal('hide');
                            // 重置表单
                            $('#addRoleForm')[0].reset();
                            // 重新加载角色列表
                            loadRoles();
                            alert('角色添加成功');
                        } else {
                            alert('角色添加失败：' + response.msg);
                        }
                    },
                    error: function() {
                        alert('角色添加失败，请稍后再试');
                    }
                });
            });
            
            // 编辑角色按钮点击事件
            $(document).on('click', '.edit-role', function() {
                const roleId = $(this).data('id');
                
                // 获取角色详情
                $.ajax({
                    url: '/roles/' + roleId,
                    type: 'GET',
                    success: function(response) {
                        if (response.code === 1) {
                            const role = response.data;
                            $('#editRoleId').val(role.id);
                            $('#editRoleName').val(role.name);
                            
                            // 加载权限并设置选中状态
                            loadPermissions('editPermissionContainer', role.permissions);
                            
                            $('#editRoleModal').modal('show');
                        } else {
                            alert('获取角色详情失败：' + response.msg);
                        }
                    },
                    error: function() {
                        alert('获取角色详情失败，请稍后再试');
                    }
                });
            });
            
            // 更新角色
            $('#updateRoleBtn').click(function() {
                const id = $('#editRoleId').val();
                const name = $('#editRoleName').val();
                
                if (!name) {
                    alert('请填写角色名称');
                    return;
                }
                
                // 获取选中的权限
                const permissionSet = [];
                $('#editPermissionContainer .permission-checkbox:checked').each(function() {
                    permissionSet.push({
                        id: parseInt($(this).val())
                    });
                });
                
                const roleData = {
                    id: parseInt(id),
                    name: name,
                    permissionSet: permissionSet
                };
                
                $.ajax({
                    url: '/roles',
                    type: 'PUT',
                    contentType: 'application/json',
                    data: JSON.stringify(roleData),
                    success: function(response) {
                        if (response.code === 1) {
                            // 关闭模态框
                            $('#editRoleModal').modal('hide');
                            // 重新加载角色列表
                            loadRoles();
                            alert('角色更新成功');
                        } else {
                            alert('角色更新失败：' + response.msg);
                        }
                    },
                    error: function() {
                        alert('角色更新失败，请稍后再试');
                    }
                });
            });
            
            // 删除角色按钮点击事件
            $(document).on('click', '.delete-role', function() {
                const roleId = $(this).data('id');
                $('#deleteRoleId').val(roleId);
                $('#deleteRoleModal').modal('show');
            });
            
            // 确认删除角色
            $('#confirmDeleteBtn').click(function() {
                const roleId = $('#deleteRoleId').val();
                
                $.ajax({
                    url: '/roles/' + roleId,
                    type: 'DELETE',
                    success: function(response) {
                        if (response.code === 1) {
                            // 关闭模态框
                            $('#deleteRoleModal').modal('hide');
                            // 重新加载角色列表
                            loadRoles();
                            alert('角色删除成功');
                        } else {
                            alert('角色删除失败：' + response.msg);
                        }
                    },
                    error: function() {
                        alert('角色删除失败，请稍后再试');
                    }
                });
            });
            
            // 搜索表单提交
            $('#searchForm').submit(function(event) {
                event.preventDefault();
                const name = $('#roleName').val();
                // 这里可以根据需要实现角色搜索功能
                // 当前后端未提供按名称搜索的接口，暂时刷新全部角色列表
                loadRoles();
            });
            
            // 重置按钮点击事件
            $('#resetBtn').click(function() {
                $('#roleName').val('');
                loadRoles();
            });
        });
    </script>
</body>
</html> 